import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

const service = axios.create({
  baseURL: 'http://101.34.248.54:8092/api/'
});

service.interceptors.request.use(
  function(config) {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    // token过期
    if (error.response && error.response.status === 401) {
      router.push({ path: '/login' });
    }
    return Promise.reject(error);
  }
);

export default service;
